package action.user;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import org.hibernate.*;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;

import db.*;

@SuppressWarnings("serial")
public class BidAction extends ActionSupport implements Preparable{
	private Bid bd;
	private String bd_type;
	private List<String> bd_types;
	private String newBD_trId;
	private String new_BId;
	
	public void prepare() {
		bd_types = new ArrayList<String>();
		bd_types.add("Seller's");
		bd_types.add("Buyer's");
    }
	
	public Bid getBd() {
		return bd;
	}

	public void setBd(Bid bd) {
		this.bd = bd;
	}

	public String getBd_type() {
		return bd_type;
	}

	public void setBd_type(String bdType) {
		bd_type = bdType;
	}

	public List<String> getBd_types() {
		return bd_types;
	}

	public void setBd_types(List<String> bdTypes) {
		bd_types = bdTypes;
	}

	public String getNewBD_trId() {
		return newBD_trId;
	}

	public void setNewBD_trId(String newBDTrId) {
		newBD_trId = newBDTrId;
	}

	public String getNew_BId() {
		return new_BId;
	}

	public void setNew_BId(String newBId) {
		new_BId = newBId;
	}

	@SuppressWarnings("unchecked")
	public String add(){
		Map session = ActionContext.getContext().getSession();		
		Integer trId = Integer.parseInt(this.getNewBD_trId());
		TransactionDAO trDao = new TransactionDAO();
		db.Transaction temp_tr = trDao.findById(trId);
		Integer bd_uid = temp_tr.getServiceContract().getUId();
		String userId = (String)session.get("userId");
		Integer uId = Integer.parseInt(userId);
		if (!bd_uid.equals(uId)){
			System.out.println("Wrong privilege!");
			return ERROR;
		}
		BidDAO bdDao = new BidDAO();
		org.hibernate.Transaction trans = bdDao.getSession().beginTransaction();
		Bid bdToAdd = new Bid();
		bdToAdd.setTransaction(temp_tr);
		bdToAdd.setBStatus(0);//0 for initial, 1 for in-progress, 2 for done(after sale)
		Date now = new Date();
		now.getTime();
		bdToAdd.setBDate(now);
		//System.out.println(getBd_type().equals("Seller's"));
		int bd_type_int = (getBd_type().equals("Seller's"))?1:0; 
		bdToAdd.setBType(bd_type_int);// 1 for selling, 0 for buying
		bdToAdd.setBDescription(bd.getBDescription());
		bdDao.save(bdToAdd);
		trans.commit();
		this.setNew_BId(bdToAdd.getBId()+"");
		org.hibernate.Transaction trans2 = trDao.getSession().beginTransaction();
		Set bidSet = new HashSet();
		Set tempSet = temp_tr.getBids();
		if (tempSet !=null)
			bidSet = tempSet;
		bidSet.add(bdToAdd);
		temp_tr.setBids(bidSet);
		trans2.commit();
		
		return SUCCESS;
	}
}